<?php
    
    require_once  ("Includes/connectDB.php");

    //set up regex expression:
    define("R_PLACE", '([\d\-]+)');
    define("R_TEAM", '([\w \-\']+)');
    define("R_NAME", '([\w \'\-.]+)');
    define("R_AGE",'([\d]{1,2})');
    define("R_RELAY_SWIMMER", R_NAME.',[\s]+'.R_NAME.'[\s]+'.R_AGE);
    define("R_TIME", 'x?X?([\d]{0,2}:?[\d]{2}.[\d]{2}|DQ|NS|)');
    define("R_RELAY_TEAM", '\'([\w])\'');

    define("REGEX_RELAY", '~'.R_PLACE.'\.[\s]*'.R_TEAM.'[\s]*\('.R_RELAY_SWIMMER.',[\s]*'.
                          R_RELAY_SWIMMER.',[\s]*'. R_RELAY_SWIMMER.',[\s]*'.R_RELAY_SWIMMER.'\),[\s]*'.R_TIME.';~');
    define("REGEX_SINGLE", '~'.R_PLACE.'\.[\s]*'.R_NAME.',[\s]*'.R_NAME.',[\s]*'.R_TEAM.',[\s]*'.R_TIME.';~');
    define("REGEX_RELAY_TEAM",'~([\w \-]+)(\'([\w])\')?~');

    /*if  (strstr($_SERVER['DOCUMENT_ROOT'],'ResultsManager'))
        define("ROOT_DIR", $_SERVER['DOCUMENT_ROOT'].'/');
    else
        define("ROOT_DIR", $_SERVER['DOCUMENT_ROOT'].'/seaotters/ResultsManager/'); */
    define("ROOT_DIR", getcwd().'/');

    // helper function that scans in even *** NOT FROM AP FORMAT ***
    // may be useless at this point
    function scanInEvents($filename)
    {
        global $databaseConnection;

        $file = fopen($filename, "r");
        if(!$file)
            die("Error: Can't open file");

        echo '<table>';
        // read line by line
        $eventid = 1;
        while ($line = fgetss($file))
        {
            if (!isEventTitle($line))
                continue;

            preg_match('~([\w &\-]+):~', $line, $match);
            $name = $match[1];

            /*
                $eventid = intval(strtok(" "));
                $gender = strtok(" ");
                $age = strtok(" ");          
                $tok = strtok(" ");
                if($tok == "&") {
                    $age = $age . ' & ' . strtok(" ");
                    $length = intval(strtok(" "));
                } else {
                    $length = intval($tok);
                }
                strtok(" ");
                $style = strtok(" ");
                if (strtok(" "))
                    $style = $style . " Relay";
            */

            // check for existing id:
            $query = "SELECT id FROM events WHERE id = ?";
            $statement = $databaseConnection->prepare($query);
            $statement->bind_param('i', $eventid);
            $statement->execute();
            $statement->store_result();

            if ($statement->error)
                die('Database query failed: ' . $statement->error);

            //var_dump($statement->fetch());

            if ($statement->num_rows != 0)
                continue;

            // check for existing id:
            $query = "INSERT INTO events (event_id, name) VALUES (?, ?)";
            $statement = $databaseConnection->prepare($query);
            $statement->bind_param('is', $eventid, $name);
            $statement->execute();
            $statement->store_result();

            if ($statement->error)
                die('Database query failed: ' . $statement->error);

            echo "<tr><td>Event $eventid $name<td></tr>";
            $eventid++;
        }
        echo '</table>';

    }

    // determines if a line contains the event title
    function isEventTitle($line)
    {
        return strpos($line, ':') !== FALSE && strpos($line, '.') === FALSE;
    }

    // extracts first date match from a line, 
    define("REGEX_DATE1", '~([\d]{1,2}/[\d]{1,2}/([\d]{4}|[\d]{2}))~');
    function extractDate($line)
    {
        if (preg_match(REGEX_DATE1, $line, $datematch))
            return $datematch[0];
        else
            return NULL; 
    }

    // attempts to extract team information from a given line
    define("REGEX_TEAMS_DUAL", '~[\d]* ?([\w ]+) ?(vs.|@) ?([\w ]+)~');
    define("REGEX_TEAMS_GETNAME", '~[\d]* ?([\w /.@]+) ?~');
    function extractMeetInfo($line)
    {
        $data = array();

        if (stripos($line, "Championships"))
            $data['type'] = 3;
        else if (preg_match(REGEX_TEAMS_DUAL, $line, $teammatch))
        {
            $data['type'] = 2;
            $data['awayteam'] = trim($teammatch[1]); 
            $data['hometeam'] = trim($teammatch[3]);
        }
        else
            $data['type'] = 1;

        if (preg_match(REGEX_TEAMS_GETNAME, $line, $teammatch))
            $data['name'] = trim($teammatch[1]);
        else
            return NULL;

        return $data;
    }

    // scans standard news paper format file, return key/value array
    function parseAPFile($filename, $printout = FALSE) {
        
        $file = fopen($filename, 'r');
        if ($file === FALSE) {
            echo 'Error: Cannot open file';
            return FALSE;
        }

       // attempt to scan in meet data
        $file = fopen($filename, 'r');
        while (!isEventTitle($line = fgets($file)) && $line !== FALSE) {
            if(!isset($metadata))
                $metadata = extractMeetInfo($line);
            if (!isset($date))
                $date = extractDate($line);
        }

    // ******* PARSE OUT RECORDS ******* //
        $scores = array();
        while ($line !== FALSE) {
            
            // is this a relay or not?
            if (stripos($line, 'relay') === FALSE)
                $isRelay = FALSE;
            else    
                $isRelay = TRUE;

            // buffer full event for regex parsing
            $event = str_replace(array("\r", "\n"), "",$line);
            while (!isEventTitle($line = fgets($file)) && $line !== FALSE)
                $event = $event . str_replace(array("\r", "\n"), "", $line);


            // count semi-colons (number of records for sanity check:
            $semicolonCount = substr_count($event, ';');
            $numScores = 0;

            // extract event name and look up event id:
            preg_match('~([\w &\-]+):~', $event, $match);
            $eventname = $match[1];
            $eventid = lookupEventIDByName($eventname);
            if (!$eventid)
            {
                echo "Error: Event ".$eventname." not found, please check file and/or database";
                return FALSE;
            }

        /******* PARSE RELAY SCORES *******/
            if ($isRelay) {
                preg_match_all(REGEX_RELAY, $event, $matches, PREG_SET_ORDER);
                foreach ($matches as $match) {
                    $numScores++;

                    //check for relay team letter:
                    preg_match(REGEX_RELAY_TEAM,trim($match[2]), $teammatch);
                    $team = trim($teammatch[1]);
                    if (isset($teammatch[3]))
                        $relay_team = $teammatch[3];
                    else   
                        $relay_team = 'A';

                    for ($i = 0; $i < 4; $i++) // one for each swimmer. 
                    {
                        $score = array(
                            "eventid" => $eventid,
                            "place" => trim($match[1]),
                            "team" => $team,
                            "lastname" => trim($match[3*$i + 3]),
                            "firstname" => trim($match[3*$i + 4]),
                            "age" => trim($match[3*$i + 5]),
                            "final" => trim($match[15]),
                            "relay" => TRUE,
                            "relay_team" => trim($relay_team),
                            "relay_pos" => $i+1,
                            "sort_pos" => (($numScores-1)*4)+$i
                        );
                        array_push($scores, $score);
                    }
                    if (is_null($match[15]))
                        echo 'Warning: Record without final time detected';
                }
            }

        /******* PARSE SINGLE SCORES *******/
            else {
                preg_match_all(REGEX_SINGLE, $event, $matches, PREG_SET_ORDER);
                foreach ($matches as $match){
                    $numScores++;
                    $score = array(
                        "eventid" => $eventid,
                        "place" => trim($match[1]),
                        "lastname" => trim($match[2]),
                        "firstname" => trim($match[3]),
                        "team" => trim($match[4]),
                        "final" => trim($match[5]),
                        "relay" => FALSE,
                        "sort_pos" => $numScores
                    );
                    array_push($scores, $score);

                    if (is_null($match[5]))
                        echo 'Warning: Record without final time detected';
                }
            }

            // sanity check
            if ($semicolonCount != $numScores) {
                echo "Error: Regex mismatch, please check event: $eventid, '$eventname'";
                return FALSE;
            }
            $eventid++;
        }

    /******* PRINT OUT MEET FOR DOUBLE CHECK *******/
        if($printout)
        {
            echo "<table>\n";
            $lastevent = -1;
            foreach($scores as $score)
            {
                // if last event id doesn't match new event id, place event header
                if($score['eventid'] != $lastevent)   {
                    echo '<tr class="headrow"><td colspan="6">'.getEventNameByID($score['eventid']).'</td></tr>';
                    $lastevent = $score['eventid'];
                }

                /* seed and final time conversion
                $final = score[''];
                if($final < $seed)
                    $improve = '!';
                else 
                    $improve = '&nbsp;';
                */

                if ($score['relay'])
                    $letter = ' \''.$score['relay_team'].'\' Pos:'.$score['relay_pos'];
                else
                    $letter = '';

                echo '<tr class="newmeet"><td></td>'; 
                echo '<td><a href="/swimmer.php?swimid=">'.$score['firstname'].' '.$score['lastname'].'</a></td>';
                echo '<td align="right"><b>'.$score['place'].'</b></td>';
                //echo '<td align="right">'.$seed.'</td>';
                echo '<td align="right"><b>'.$score['final'].'</b></td>';
                //echo "<td>$improve</td>";
                echo '<td>'.$score['team'].$letter.'</td></tr>';
            }
            echo "</table>\n";
        }

        return array(
            'metadata' => $metadata, 
            'date' => $date, 
            'scores' => $scores,
            'filename' => $filename
        );
    }

    function testScanResults($tennent)
    {
        // array of meets
        $meets = array();

        //scan all files in the directary
        //only pickup .result files
        $prev_dir = getcwd();
        chdir(ROOT_DIR.'Results/'.$tennent);
        $dir = opendir(ROOT_DIR.'Results/'.$tennent);

        echo "<table>";
        while( ($filename = readdir($dir)) !== FALSE )
        {
            echo "<tr><td>";
            if (!strpos($filename, '.results'))
                continue;

            echo $filename.'   ';
            $meetdata = parseAPFile($filename);
            echo "</td></tr>";
            if ($meetdata === FALSE) {
                echo "</table>";
                return FALSE;
            }
        }
        echo "</table>";

        closedir($dir);
        chdir($prev_dir);

        return $meets;
    }

    function restoreDatabase($tennent)
    {
        //scan all files in the directary
        //only pickup .result files
        $prev_dir = getcwd();
        chdir(ROOT_DIR.'Results/'.$tennent);
        $dir = opendir(ROOT_DIR.'Results/'.$tennent);

        echo "<table>";
        while( ($filename = readdir($dir)) !== FALSE )
        {
            set_time_limit(0);
            echo "<tr><td>";
            if (!strpos($filename, '.results'))
                continue;

            echo $filename.'   ';
            $meetdata = parseAPFile($filename);
            if ($meetdata === FALSE) {
                echo "</td></tr>";
                echo "</table>";
                return FALSE;
            }
            addWholeMeet($meetdata);
            echo "</td></tr>";
        }
        echo "</table>";

        closedir($dir);
        chdir($prev_dir);
    }

    function setupMetaData($tennent, $createDir = FALSE)
    {
        // search for tennent dir
        $foundDir = FALSE;
        $dir = opendir(ROOT_DIR.'Results');
        while (($entry = readdir($dir)) !== FALSE)
        {
            if ($entry == $tennent)
                $foundDir = TRUE;
        }

        // if dir not found, and create dir is not set, return false
        if (!$foundDir && !$createDir) {
            echo "Error: Tennent directory not found";
            return FALSE;
        }

        // if dir not found, attempt to create dir
        else if (!$foundDir) {
            if (mkdir(ROOT_DIR.'Results/'.$tennent) === FALSE){
                echo 'Error: Cannot make directory';
                return FALSE;
            }
        }

        closedir($dir);

        //scan all files in the directary
        //only pickup .csv files
        $prev_dir = getcwd();
        chdir(ROOT_DIR.'Results/'.$tennent);
        $metaFile = fopen('initdata.txt', 'w');
        $dir = opendir(ROOT_DIR.'Results/'.$tennent);
        while( ($filename = readdir($dir)) !== FALSE )
        {

            if ($pos = strpos($filename, '.csv')) {
                rename($filename, substr($filename, 0, $pos).'.results');
            }

            if (!strpos($filename, '.results'))
                continue;

            // attempt to scan in meet data
            unset($date);
            unset($meetdata);
            $file = fopen($filename, 'r');
            while (!isEventTitle($line = fgets($file)) && $line !== FALSE) {
                if(!isset($meetdata))
                    $meetdata = extractMeetInfo($line);
                if (!isset($date))
                    $date = extractDate($line);
            }
            fclose($file);

            // format team data
            if ($meetdata['type'] == 2)
                $team = "TYPE:DUAL AWAY:'".$meetdata['awayteam']."' HOME:'".$meetdata['hometeam']."'";
            else if ($meetdata['type'] == 3)
                $team = "TYPE:CHAMPS";
            else if ($meetdata['type'] == 1)
                $team = "TYPE:PRACTICE";

            // format date 
            if (!isset($date))
                $date = "DATE:<none>";
            else
                $date = "DATE:".$date;

            fwrite($metaFile, basename($filename)." ".$team." ".$date." MEETNAME:".$meetdata['name']."\n");
        }
        closedir($dir);
        fclose($metaFile);
        chdir($prev_dir);
    }

?>